package com.yjd.api.doctor;

import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.IntroDetailModel;
import com.yjd.comm.base.service.ICityService;
import com.yjd.comm.base.service.IIntroDetailService;
import com.yjd.comm.doctor.service.IDoctorService;
import com.yjd.comm.org.model.OrganizationModel;
import com.yjd.comm.org.service.IOrganizationService;
import com.yjd.comm.project.model.ProjectModel;
import com.yjd.comm.project.service.IProjectService;
import com.yjd.comm.resource.service.IResourceService;
import com.yjd.comm.tag.service.ITagService;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.util.StringUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import java.util.*;

/**
 * 医生相关操作
 * Created by yangchangyan on 2017/6/30.
 */
@Controller("com.yjd.api.doctor.DoctorControl")
@Scope("prototype")
@RequestMapping("/doctor")
public class DoctorControl extends BaseControl{

    @Resource
    private IDoctorService doctorService;

    @Resource
    private IIntroDetailService introDetailService;

    @Resource
    private IResourceService resourceService;

    @Resource
    ICityService cityService;

    @Resource
    private IOrganizationService organizationService;

    @Resource
    private ITagService tagService;

    @Resource
    private IProjectService projectService;

    /**
     * 查询医生详情
     * Created by yangchangyan on 2017/6/29.
     * @param doctor_id 医生id
     * @return void
     * @throws
     */
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    public void doctorDetail(Long doctor_id) throws Exception {

        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);

        List<Map<String, Object>> doctor = doctorService.queryDoctor(paramMap);
        if(0 == doctor.size()){
            FrameUtil.throwBaseException1("医生不存在");
        }

        // 查询医生基本信息
        Map<String, Object> doctorResult = doctor.get(0);

        // 医生详情介绍
        IntroDetailModel intro = introDetailService.getModelById(doctorResult.get("detail_id"), DbWREnums.READ);
        doctorResult.put("detail", null == intro ? "" : intro.getContent());

        // 生成返回信息
        paramMap.put("doctor", doctorResult);
        this.successData(paramMap);
    }

    /**
     * 查询医生负责的项目
     * Created by yangchangyan on 2017/6/29.
     * @param doctor_id 医生id
     * @return void
     * @throws
     */
    @RequestMapping(value = "/project", method = RequestMethod.POST)
    public void doctorResProject(Long doctor_id, int page, int rows) throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);

        List<Map<String, Object>> doctors = doctorService.queryDoctor(FrameUtil.newHashMap("doctor_id", doctor_id));
        if(doctors.size() == 0){
            FrameUtil.throwBaseException1("医生不存在");
        }
        paramMap.put("doctor", doctors.get(0));
        paramMap.put("project", projectService.queryProject(paramMap));
        this.successData(paramMap);
    }

    /**
     * 根据机构id查医生
     * Created by yangchangyan on 2017/7/10.
     * @param org_id 机构id
     * @return void
     * @throws
     */
    @RequestMapping(value = "/with_org", method = RequestMethod.POST)
    public void queryDoctorByOrg(Long org_id) throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        paramMap.put("org_id", org_id);
        paramMap.put("doctor", doctorService.queryDoctor(paramMap));
        this.successData(paramMap);
    }

    /**
     * 根据地区查询医生，支持分页查询
     * Created by yangchangyan on 2017/7/7.
     * @param regionId 地区ID
     * @param page 查询第page页
     * @param rows 每页展示rows条数据
     * @throws
     */
    @RequestMapping(value = "/all", method = RequestMethod.POST)
    public void allDoctor(Long regionId, int page, int rows) throws Exception {
        // 如果地区id没有，则默认返回全国范围的机构分布信息
        if(null == regionId){
            regionId = Long.valueOf(0L);
        }

        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);

        Long category_id = 0L;
        if( null != paramMap.get("category_id")){
            if(StringUtil.isNotEmpty(paramMap.get("category_id").toString())){
                try{
                    category_id = Long.parseLong(paramMap.get("category_id").toString());
                } catch (Exception e){
                    FrameUtil.throwBaseException1("项目分类错误");
                }
            }
        }

        List<ProjectModel> projects = null;
        if( category_id == 0){
            projects = projectService.getModelList(FrameUtil.newHashMap(), DbWREnums.READ);
        } else {
            projects = projectService.getModelList(FrameUtil.newHashMap("category_id", category_id), DbWREnums.READ);
        }
        // 没有对应分类的项目，直接返回
        if(null ==projects || projects.size() == 0){
            paramMap.put("doctor", ArrayUtils.EMPTY_OBJECT_ARRAY);
            this.successData(paramMap);
            return;
        }

        Set<Long> doctor_ids = new HashSet<Long>();
        for(ProjectModel p: projects){
            doctor_ids.add(p.getDoctor_id());
        }
        paramMap.put("doctor_ids", Arrays.asList(doctor_ids.toArray()));

        // 返回全国范围的医生分布信息（即调用/doctor/all接口）
        if(0 == regionId){
            paramMap.put("doctor", doctorService.queryDoctor(paramMap));
            paramMap.remove("doctor_ids");
            this.successData(paramMap);
            return;
        }

        // 查询所有regionId下面的所有三级城市id
        List<Long> ids = new ArrayList<Long>();
        ids = cityService.querySubCities(regionId, ids);

        // 查询ids城市中的机构
        paramMap.put("org_city_ids", ids);
        List<OrganizationModel> orgs = organizationService.getModelList(paramMap, DbWREnums.READ);
        paramMap.remove("org_city_ids");
        if(orgs.size() == 0){
            paramMap.put("doctor", ArrayUtils.EMPTY_OBJECT_ARRAY);
            this.successData(paramMap);
            return;
        }

        // 更加机构id查询出对应的医生
        ids.clear();
        for(OrganizationModel org:orgs){
            ids.add(org.getOrg_id());
        }
        paramMap.put("org_ids", ids);
        paramMap.put("doctor", doctorService.queryDoctor(paramMap));
        paramMap.remove("org_ids");

        paramMap.remove("doctor_ids");

        this.successData(paramMap);
    }
}
